package com.xstablet.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dayi.bean.BaseBean;
import com.dayi.view.VerticalData;
import com.dayi.view.VerticalScrollView;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.NormalDialog;
import com.lib.fastkit.views.recyclerview.tool.MyLinearLayoutManager;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;
import com.lihang.ShadowLayout;
import com.luck.picture.lib.tools.ToastManage;
import com.xstablet.R;
import com.xstablet.bean.CareStateBean;
import com.xstablet.bean.MainInfoBean_1;
import com.xstablet.bean.ServiceTeacherListBean;
import com.xstablet.bean.TeacherAskListBean;
import com.xstablet.bean.newdayi.QueryStudentRestMoneyBean;
import com.xstablet.bean.newdayi.TeacherListBean;
import com.xstablet.util.TeacherListPopup;
import com.xstablet.view.popuputil.AutoPollRecyclerView;
import com.xstablet.view.popuputil.TabletMoneyTypePopup;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import bean.SubjectBean;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2020/7/15 0015.
 */

@SuppressLint("ValidFragment")
public class MainStudentFragment extends BaseAppFragment {

    @BindView(R.id.lin_teacherlist)
    LinearLayout linTeacherlist;
    @BindView(R.id.iv_before)
    ImageView ivBefore;
    @BindView(R.id.rv_teacher)
    RecyclerView rvTeacher;
    @BindView(R.id.iv_next)
    ImageView ivNext;

    @BindView(R.id.sl_ask)
    ShadowLayout slAsk;
    @BindView(R.id.iv_ask)
    ImageView ivAsk;
    @BindView(R.id.sl_list)
    ShadowLayout slList;
    @BindView(R.id.tv_errornum)
    TextView tvErrornum;
    @BindView(R.id.sl_listen)
    ShadowLayout slListen;

    @BindView(R.id.tv_morerecord)
    TextView tvMorerecord;
    @BindView(R.id.rv_record)
    AutoPollRecyclerView rvRecord;

    @BindView(R.id.tv_morevideo)
    TextView tvMorevideo;
    @BindView(R.id.rv_video)
    RecyclerView rvVideo;

    @BindView(R.id.lin_more_record)
    LinearLayout linMoreRecord;
    @BindView(R.id.sl_more_video)
    CardView slMoreVideo;

    //     AI作业辅导部分     学生上传作业以及等待
    @BindView(R.id.iv_connent)//学生重连入口
            ImageView ivReconnect;

    //     AI作业辅导部分     学生上传作业以及等待
    @BindView(R.id.iv_wait)
    ImageView ivWait;
    @BindView(R.id.fr_ai)//AI父布局
            FrameLayout frAI;

    @BindView(R.id.fr_gift)
    FrameLayout frGift;
    @BindView(R.id.iv_delete)
    ImageView ivDeleteGift;
    @BindView(R.id.tv_gift)
    TextView tvGift;
    @BindView(R.id.iv_gift)
    ImageView ivGift;

    @BindView(R.id.tv_ai_toclass)
    TextView tvAiToclass;
    @BindView(R.id.vl_msg)
    VerticalScrollView vlMsg;

    @BindView(R.id.lin_wait)
    LinearLayout linWait;

    @BindView(R.id.lin_study)
    LinearLayout linStudy;
    @BindView(R.id.iv_AI)
    ImageView ivAi;

    @BindView(R.id.iv_listen)
    ImageView ivListen;

    //首页老师、尖课、短视频适配器
    TeacherInfoAdapter teacherAdapter;
    ShortVideoInfoAdapter videoAdapter;

    //首页老师、尖课、短视频数据容器
    List<TeacherAskListBean.ObjBean.DataBean> teacherList = new ArrayList<>();
    List<MainInfoBean_1.ObjBean.RecordingClassBean> recordList = new ArrayList<>();
    List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> videoList = new ArrayList<>();

    MainInfoBean_1.ObjBean.CourseOrderBean courseOrderBean;

    //选择条件以及老师列表弹出框
    TeacherListPopup teacherListPopup;

    public int currentPosition = 0;

    public View parentView;

    //装载科目的实体类和字符串
    private SubjectBean subjectBean;
    private String chooseSubjectStr = "";
    private String chooseSubjectId = "";
    //年级、科目字典装载容器
    private List<String> mDataCourse = new ArrayList<>();

    MainStudentFragment mainInfoFragment;

    AutoPollAdapter autoPollAdapter;

    private String[] gradeArr;

    private View popupShowView;

    //第一次登录显示套餐情况，以及充值后显示充值次数
    TabletMoneyTypePopup typePopup;
    //套餐具体情况
    String package_content;

    @SuppressLint("ValidFragment")
    public MainStudentFragment(String package_content) {

        this.package_content = package_content;
    }

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        mainInfoFragment = this;

        this.popupShowView = view;

        initView();

        //获取首页数据
        initMainInfoData();

        //获取连线答疑数据
        initTeacherAskList();

        initPopupView();

        //初始化学科字典
        initCourseList();

        //初始化老师列表
        initTeacherAskList();

        gradeArr = getActivity().getResources().getStringArray(R.array.array_choose_subject);

        //判断套餐情况是否为空，不为空则显示第一次进入欢迎弹出框
        if (StringUtil.isNotEmpty(package_content, true)) {

            LogUtil.e("用户套餐的数据为：" + package_content);
            showTabletIsRecharge(0, package_content, 0);
        }
    }

    //判断底部显示Ai上传作业还是等待
    private void initAIUploadOrWait() {

//        linWait.setVisibility(View.GONE);
//        linStudy.setVisibility(View.VISIBLE);

        //如果Course_id不为空，代表学生异常退出，需要重连进入直播间
        if (StringUtil.isNotEmpty(courseOrderBean.getCourse_id(), true)) {

            LogUtil.e("学生断线重连");
            frAI.setVisibility(View.GONE);
            ivReconnect.setVisibility(View.VISIBLE);
        } else {

            ivReconnect.setVisibility(View.GONE);
            frAI.setVisibility(View.VISIBLE);

            int wait = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getIsWait();
            LogUtil.e("是否显示等到的值为：" + wait);
            //显示等待部分
            if (1 == wait) {

                linWait.setVisibility(View.VISIBLE);
                linStudy.setVisibility(View.GONE);
                //初始化等待动态图
                initWaitGif();

            } else {

                linWait.setVisibility(View.GONE);
                linStudy.setVisibility(View.VISIBLE);
                //初始化红包动态图
                initGiftGif();
            }
        }

    }


    private void initGiftGif() {

        Glide.with(this).load(R.drawable.gift_main).listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                if (resource instanceof GifDrawable) {
                    //加载一次
                    ((GifDrawable) resource).setLoopCount(-1);
                }

                return false;
            }

        }).into(ivGift);
    }

    private void initWaitGif() {

        Glide.with(this).load(R.drawable.icon_wait_main).listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                if (resource instanceof GifDrawable) {
                    //加载一次
                    ((GifDrawable) resource).setLoopCount(-1);
                }

                return false;
            }

        }).into(ivWait);

    }


    private void initTeacherAskList() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "RECOMMENDED_TEACHER_LIST")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<TeacherAskListBean>() {
                    @Override
                    public void onSuccess(TeacherAskListBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                //设置提问数量
                                if (result.getObj().getQuestionNum() > -1) {
                                    tvErrornum.setText(result.getObj().getQuestionNum() + "");
                                } else {
                                    tvErrornum.setText("0");
                                }

                                if (result.getObj().getData() != null) {
//                                    initTeacherInfo(result.getObj().getOnline_answer());
                                    if (teacherList.size() > 0) {
                                        teacherList.clear();
                                    }
                                    teacherList.addAll(result.getObj().getData());
                                    teacherAdapter.notifyDataSetChanged();
                                }
                            }
                        } else {
                        }
                    }

                    @Override
                    public void onError(String e) {
                    }
                });


    }

    @Override
    public void onResume() {
        super.onResume();

        if (mainInfoFragment.getUserVisibleHint()) {
            initMainInfoData();

            if (0 == SharedPreferenceManager.getInstance(getActivity()).getUserCache().getIsFirtShowMainFragment()) {
                showTabletIsRecharge(0, package_content, 0);
            }
        }
    }

    private void initPopupView() {

        typePopup = new TabletMoneyTypePopup(getActivity());

        teacherListPopup = new TeacherListPopup(getActivity());
        teacherListPopup.setConnectTeacherListener(new TeacherListPopup.ConnectTeacherListener() {
            @Override
            public void onConnectTeacher(ServiceTeacherListBean.ObjBean.DataBean teacherBean) {
                //用户确定教师，并返回教师信息，即将进入直播间
//                showToast(courseId + "" + coursetype + "");

                //发送连线数据至后台，记录订单数据
//                sendConnectInfoToService(teacherBean);
                teacherListPopup.dismiss();

                //查询学生兔币是否足够，不足的提示充值，足够则进入等待
                getStudentRestMoney(teacherBean);

            }
        });
    }


    public void getStudentRestMoney(ServiceTeacherListBean.ObjBean.DataBean teacherBean) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "STUDENT_REMAINING_RABBIT_COINS")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<QueryStudentRestMoneyBean>() {
                    @Override
                    public void onSuccess(QueryStudentRestMoneyBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj().getTotal() > 0) {
                                if (result.getObj().getTotal() >= 4) {
                                    CoachAIStudyDialog.getInstance()
                                            .setTitle("温馨提示")
                                            .setContent("为保证连线质量，本次提问需暂压3个兔币，连线结束时将退回到您的余额中，是否确定继续连线老师？")
                                            .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                                                @Override
                                                public void onCancel() {

                                                }
                                            })
                                            .setSureListener(new CoachAIStudyDialog.SurelListener() {
                                                @Override
                                                public void onSure() {
                                                    //因需要多端登录，为保证推送的准确性，需要先确定推送的设备
                                                    bindYouMengToken();

                                                    ARouter.getInstance().build(ARouterPathUtils.Tablet_DaYi_StudentConnectWaitActivity)
                                                            .withInt("teacherId", teacherBean.getId())
                                                            .withString("chooseSubjectId", chooseSubjectId)
                                                            .navigation();
                                                }
                                            }).show(getFragmentManager());
                                } else if (result.getObj().getTotal() < 4) {

                                    CoachAIStudyDialog.getInstance()
                                            .setTitle("温馨提示")
                                            .setContent("您的兔币已不足，请在学思兔手机APP充值后再进行提问！")
                                            .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                                                @Override
                                                public void onCancel() {
                                                }
                                            })
                                            .setSureListener(new CoachAIStudyDialog.SurelListener() {
                                                @Override
                                                public void onSure() {

                                                }
                                            }).show(getFragmentManager());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    private void bindYouMengToken() {

        if (StringUtil.isNotEmpty(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getYouMengPushToken(), true)) {
            LogUtil.e("@@@@@@@@@@@@@@@@@@@@@@@" + SharedPreferenceManager.getInstance(getActivity()).getUserCache().getYouMengPushToken());
            HttpUtils.with(getActivity())
                    .addParam("requestType", "SET_APPID")
                    .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                    .addParam("app_id", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getYouMengPushToken())
                    .addParam("client", "XSTTablet")
                    .execute(new HttpNormalCallBack<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean result) {

                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }
    }


    /**
     * 将String科目字符串转为相对应的科目Id
     *
     * @param subjectBean
     * @param str
     * @return
     */
    private String getSubjectId(SubjectBean subjectBean, String str) {

        for (int i = 0; i < subjectBean.getObj().size(); i++) {
            if (str.equals(subjectBean.getObj().get(i).getName())) {
                return subjectBean.getObj().get(i).getId();
            }
        }

        return null;
    }

    /**
     * 获取科目字典数据
     */
    private void initCourseList() {
        mDataCourse.clear();
        HttpUtils.with(getActivity())
                .addParam("requestType", "DICT_SUBJECT_LIST")
                .execute(new HttpNormalCallBack<SubjectBean>() {
                    @Override
                    public void onSuccess(SubjectBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {

                            subjectBean = result;
                            for (int i = 0; i < result.getObj().size(); i++) {
                                mDataCourse.add(result.getObj().get(i).getName());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }


    private void showChooseDialog() {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_askchoose, null);

        ImageView iv_hide = view.findViewById(R.id.new_iv_hide);
        Spinner spinSubj = view.findViewById(R.id.new_spin_grade);
        spinSubj.setDropDownVerticalOffset(112);

        try {
            Field popup = Spinner.class.getDeclaredField("mPopup");
            popup.setAccessible(true);
            // Get private mPopup member variable and try cast to ListPopupWindow
            ListPopupWindow popupWindow = (ListPopupWindow) popup.get(spinSubj);
            // Set popupWindow height to 500px
            popupWindow.setHeight(600);
        } catch (Exception e) {
            // silently fail...
            LogUtil.e("Exception为：" + e.getMessage().toString());
        }

        spinSubj.setAdapter(new TvArrayAdapter(getActivity(), gradeArr));

        LinearLayout linPay = view.findViewById(R.id.new_lin_pay);
        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setView(view)
                .setCancelable(true)
                .show();

        spinSubj.setOnItemSelectedListener(new SubjectSpinnerAdapter());

        iv_hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        linPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(chooseSubjectStr)) {
                    showToast("选择年级之后才能连线老师哦");
                    return;
                } else {

                    LogUtil.e("选择的年级是：" + chooseSubjectStr);
                    chooseSubjectId = getSubjectId(subjectBean, chooseSubjectStr);

                    if (StringUtil.isNotEmpty(chooseSubjectId, true)) {
                        LogUtil.e("选择的科目的Id是：" + chooseSubjectId);
                        //askChoosePopupUtil.dismiss();
                        dialog.dismiss();
                        getServiceTeacherList();
                    }
                }
            }
        });

    }


    private void initView() {

        teacherAdapter = new TeacherInfoAdapter(getActivity(), teacherList);
        MyLinearLayoutManager manager = new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.HORIZONTAL, false);
        rvTeacher.setAdapter(teacherAdapter);
        rvTeacher.setLayoutManager(manager);

//        recordAdapter = new RecordClassInfoAdapter(getActivity(), recordList);
        autoPollAdapter = new AutoPollAdapter(getActivity(), recordList);
        MyLinearLayoutManager manager1 = new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.HORIZONTAL, false);
//        rvRecord.setAdapter(recordAdapter);
        rvRecord.setLayoutManager(manager1);
        rvRecord.setAdapter(autoPollAdapter);
        if (true) {//保证itemCount的总个数宽度超过屏幕宽度->自己处理
            rvRecord.start();
        }

        videoAdapter = new ShortVideoInfoAdapter(getActivity(), videoList);
        MyLinearLayoutManager manager2 = new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.HORIZONTAL, false);
        rvVideo.setAdapter(videoAdapter);
        rvVideo.setLayoutManager(manager2);

        rvVideo.setOnScrollListener(new RecyclerView.OnScrollListener() {
            //用来标记是否正在向最后一个滑动
            boolean isSlidingToLast = false;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        //加载更多功能的代码
//                        slMoreVideo.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dx > 0) {
                    //大于0表示正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0表示停止或向左滚动
                    isSlidingToLast = false;
//                    slMoreVideo.setVisibility(View.GONE);
                }
            }
        });

    }

    @OnClick({R.id.iv_before, R.id.iv_next, R.id.tv_morevideo, R.id.iv_AI, R.id.iv_delete, R.id.tv_ai_toclass,
            R.id.tv_morerecord, R.id.sl_ask, R.id.sl_listen, R.id.sl_list, R.id.sl_more_video, R.id.iv_connent})
    public void onViewClicked(View view) {
        int i = view.getId();

        if (i == R.id.iv_before) {

            if (currentPosition == 0) {
                ToastManage.s(getActivity(), "当前已经是第一个了");
                return;
            } else {
                --currentPosition;
                rvTeacher.scrollToPosition(currentPosition);
            }

        } else if (i == R.id.iv_next) {

            if (currentPosition == teacherAdapter.getItemCount() - 1) {
                ToastManage.s(getActivity(), "当前已经是最后一个了");
                return;
            } else {
                ++currentPosition;
                rvTeacher.scrollToPosition(currentPosition);
            }
        } else if (i == R.id.tv_morevideo) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_ShortVideoListActivity)
                    .navigation();

        } else if (i == R.id.tv_morerecord) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_JianKe_JianKeListActivity)
                    .navigation();

        } else if (i == R.id.sl_ask) {

            ARouter.getInstance().build(ARouterPathUtils.Dayi_AskQuestionActivity)
                    .navigation();
        } else if (R.id.sl_listen == i) {

            ARouter.getInstance().build(ARouterPathUtils.Dayi_PrivateAskActivity)
                    .navigation();
        } else if (R.id.sl_list == i) {

            ARouter.getInstance().build(ARouterPathUtils.Dayi_StudentQuestionListActivity)
                    .navigation();
        } else if (i == R.id.sl_more_video) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_ShortVideoListActivity)
                    .navigation();
        } else if (i == R.id.iv_AI) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_DaYi_CoachUploadAskActivity).navigation();
        } else if (i == R.id.tv_ai_toclass) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_DaYi_CoachUploadAskActivity).navigation();
        } else if (i == R.id.iv_delete) {

            frGift.setVisibility(View.GONE);
        } else if (i == R.id.iv_connent) {

            if (StringUtil.isNotEmpty(courseOrderBean.getCourse_type() + "", true) ||
                    StringUtil.isNotEmpty(courseOrderBean.getCourse_id(), true)) {

                goToClass(courseOrderBean.getCourse_type() + "", courseOrderBean.getCourse_id(),
                        courseOrderBean.getUuid() + "", courseOrderBean.getRoomToken(),
                        courseOrderBean.getRoomName() + "", courseOrderBean.getTeacherPhone(),
                        courseOrderBean.getUserPhone() + "", courseOrderBean.getWhitetoken());
            }
        }
    }

    //学生重连进入直播间
    private void goToClass(final String course_type, final String course_id,
                           final String uuid, final String roomToken,
                           final String roomName, final String teacherPhone,
                           final String userPhone, final String whitetoken) {

        LogUtil.e("teacherPhone=" + teacherPhone +
                "roomName=" + roomName + "uuid=" + uuid
                + "roomToken的值为：" + roomToken);

        ARouter.getInstance().build(ARouterPathUtils.Tablet_CoachStudyLivingActivity)
                .withString("roomToken", roomToken)
                .withString("uuid", uuid)
                .withString("teacherPhone", teacherPhone)
                .withString("roomName", roomName)
                .withString("userPhone", userPhone)
                .withString("whitetoken", whitetoken)
                .withString("course_id", course_id)
                .navigation();

    }

    private void initMainInfoData() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "TABLET_HOME_DATA")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<MainInfoBean_1>() {
                    @Override
                    public void onSuccess(MainInfoBean_1 result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                //设置提问数量
                                if (result.getObj().getTotal_question() > -1) {
                                    tvErrornum.setText(result.getObj().getTotal_question() + "");
                                }

                                if (result.getObj().getCourse_order() != null) {
                                    courseOrderBean = result.getObj().getCourse_order();

                                    initAIUploadOrWait();
                                }

                                //初始化录播课数据
                                if (result.getObj().getRecording_class() != null) {
//                                    initRecordInfo(result.getObj().getRecording_class());
                                    if (recordList.size() > 0) {
                                        recordList.clear();
                                    }
                                    recordList.addAll(result.getObj().getRecording_class());
//                                    recordAdapter.notifyDataSetChanged();
                                    autoPollAdapter.notifyDataSetChanged();
                                }

                                //初始化短视频数据
                                if (result.getObj().getTeacher_short_video() != null) {
//                                    initShortVideoInfo(result.getObj().getTeacher_short_video());
                                    if (videoList.size() > 0) {
                                        videoList.clear();
                                    }
                                    videoList.addAll(result.getObj().getTeacher_short_video());
                                    videoAdapter.notifyDataSetChanged();
                                }

                                //初始化平板套餐数据
                                if (result.getObj().getWhether_to_recharge() > 0) {

                                    if (1 == result.getObj().getWhether_to_recharge()) {
                                        if (result.getObj().getRecharge() != null) {

                                            String rechargeJson = MGson.newGson().toJson(result.getObj().getRecharge());
                                            LogUtil.e("用户充值的数据为：" + rechargeJson);
                                            showTabletIsRecharge(1, rechargeJson, result.getObj().getSurplus_classes());
                                        }
                                    }
                                }

                                //初始化滚动条数据
                                if (result.getObj().getScroll_barData() != null) {

                                    initVerticalData(result.getObj().getScroll_barData());
                                }

                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }


    private void showTabletIsRecharge(int type, String dataJson, int restNum) {

        typePopup.updateTypeData(type, dataJson, restNum);
        typePopup.showAnswerPopuPopu(popupShowView);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_student;
    }


    /**
     * 滚动条
     *
     * @param
     */
    private void initVerticalData(List<MainInfoBean_1.ObjBean.ScrollBarDataBean> scrollBarDataBeans) {

        List<VerticalData> list = new ArrayList<>();

        for (int i = 0; i < scrollBarDataBeans.size(); i++) {

            list.add(new VerticalData(scrollBarDataBeans.get(i).getExplanation(),
                    scrollBarDataBeans.get(i).getCreation_date()));

        }

        vlMsg.setViews(0, list);
    }


    class TeacherInfoAdapter extends BaseAdapter<TeacherAskListBean.ObjBean.DataBean> {

        public TeacherInfoAdapter(Context context, List<TeacherAskListBean.ObjBean.DataBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_teacher;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<TeacherAskListBean.ObjBean.DataBean> mData) {

            ImageView ivUser = holder.getView(R.id.iv_user);
            ImageView ivPhone = holder.getView(R.id.iv_phone);

            if (StringUtil.isNotEmpty(mData.get(position).getPhoto_url(), true)) {
                Glide.with(getActivity())
                        .load(mData.get(position).getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

//            if (StringUtil.isNotEmpty(mData.get(position).getUser_name(), true)) {
//                holder.setText(R.id.tv_name, mData.get(position).getUser_name());
//            }

//            if (StringUtil.isNotEmpty(mData.get(position).getGrade_name(), true)
//                    || StringUtil.isNotEmpty(mData.get(position).getSubject_name(), true)) {
//
//                holder.setText(R.id.tv_class, mData.get(position).getSubject_name());
//            }

//            initPhoneGif(ivPhone);

            holder.getView(R.id.lin_connect).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    parentView = v;
                    showChooseDialog();

                }
            });

        }
    }

    private void initPhoneGif(ImageView ivPhone) {

        Glide.with(this).load(R.drawable.phone).listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                if (resource instanceof GifDrawable) {
                    //加载一次
                    ((GifDrawable) resource).setLoopCount(-1);
                }

                return false;
            }

        }).into(ivPhone);

    }

    /**
     * 根据年级、科目查找老师列表
     */
    private void getServiceTeacherList() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "RECOMMENDED_TEACHER_LIST")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("subject_id", chooseSubjectId)
                .execute(new HttpNormalCallBack<ServiceTeacherListBean>() {
                    @Override
                    public void onSuccess(ServiceTeacherListBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                teacherListPopup.setTeacherListData(result.getObj().getData());
                                teacherListPopup.setTvState("已为您找到" + result.getObj().getData().size() + "位老师");
                                teacherListPopup.showAnswerPopuPopu(parentView);
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }

                });

    }

    class ShortVideoInfoAdapter extends BaseAdapter<MainInfoBean_1.ObjBean.TeacherShortVideoBean> {

        public ShortVideoInfoAdapter(Context context, List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_video;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> mData) {

            FrameLayout linVideo = holder.getView(R.id.fr_video);
//            int screenWidth = DisplayUtil.getScreenWidth(getActivity());
//            ViewGroup.LayoutParams params = linVideo.getLayoutParams();
//            params.width = screenWidth / 6;
//            linVideo.setLayoutParams(params);

            MainInfoBean_1.ObjBean.TeacherShortVideoBean teacherVideoBean = mData.get(position);
            ImageView ivUser = holder.getView(R.id.iv_user);
            if (StringUtil.isNotEmpty(mData.get(position).getPhoto_url(), true)) {
                Glide.with(getActivity())
                        .load(mData.get(position).getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            ivUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    ARouter.getInstance().build(ARouterPathUtils.Tablet_User_InfoActivity)
                            .withInt("teacherId", teacherVideoBean.getUser_id()).navigation();
                }
            });

            if (StringUtil.isNotEmpty(teacherVideoBean.getUser_name(), true)) {
                holder.setText(R.id.tv_video_username, teacherVideoBean.getUser_name());
            }
            if (StringUtil.isNotEmpty(teacherVideoBean.getPublish_date(), true)) {
                holder.setText(R.id.tv_video_usertime, teacherVideoBean.getPublish_date());
            }
            if (StringUtil.isNotEmpty(teacherVideoBean.getDynamic_content(), true)) {
                holder.setText(R.id.tv_video_content, teacherVideoBean.getDynamic_content());
            }

            //关注状态
            TextView tvCare = holder.getView(R.id.tv_video_care);
            if (1 == teacherVideoBean.getAttention_status()) {
                tvCare.setText("已关注");
                tvCare.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                tvCare.setTextColor(getActivity().getResources().getColor(R.color.newshare_care));
            }
            tvCare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //传递关注/取关到服务器
                    sendCareStateToService(tvCare, teacherVideoBean.getUser_id());
                }
            });

            ImageView ivVideoBg = holder.getView(R.id.iv_video);
            if (StringUtil.isNotEmpty(teacherVideoBean.getDynamic_hash_icon(), true)) {
                Glide.with(getActivity())
                        .load(teacherVideoBean.getDynamic_hash_icon())
                        .apply(GlideConfig.getRoundOptions(10))
                        .into(ivVideoBg);
            }

            holder.setOnClickListener(R.id.lin_info, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    ARouter.getInstance().build(ARouterPathUtils.Tablet_User_InfoActivity)
                            .withInt("teacherId", teacherVideoBean.getUser_id()).navigation();
                }
            });

            linVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int teacher_id = teacherVideoBean.getUser_id();
                    int dynamic_id = teacherVideoBean.getDynamic_id();
                    ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_ShortVideoDetailActivity)
                            .withInt("teacher_id", teacher_id)
                            .withInt("dynamic_id", dynamic_id).navigation();

//                    int recordId = mData.get(position).getId();
//                    ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
//                            .withInt("recordId", recordId).navigation();

                }
            });

        }
    }

    public void sendCareStateToService(TextView tvCare, int userId) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "DYNAMIC_ATTENTION")
                .addParam("be_user_id", userId + "")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<CareStateBean>() {
                    @Override
                    public void onSuccess(CareStateBean result) {

                        if (result != null) {
                            if (CodeUtil.CODE_200 == result.getCode()) {
                                if (0 == result.getObj().getAttention_status()) {
                                    tvCare.setText("关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_care_r_20);
                                    tvCare.setTextColor(getActivity().getResources().getColor(R.color.white));

                                } else if (1 == result.getObj().getAttention_status()) {
                                    tvCare.setText("已关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                                    tvCare.setTextColor(getActivity().getResources().getColor(R.color.newshare_care));
                                }
                                showToast(result.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {
                        LogUtil.e(e.toString());
                    }
                });
    }

    public class TvArrayAdapter extends android.widget.BaseAdapter {

        private String[] mStringArray;
        private Context context;

        public TvArrayAdapter(Context context, String[] mStringArray) {
            this.context = context;
            this.mStringArray = mStringArray;
        }

        @Override
        public int getCount() {
            return mStringArray.length;
        }

        @Override
        public Object getItem(int position) {
            return mStringArray[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {

//            LayoutInflater inflate1 = LayoutInflater.from(context);
//            View view = inflate1.inflate(R.layout.popup_gradesubjselect, null);
//
//            RecyclerView rvSelect = view.findViewById(R.id.rv_select);
//            SelectAdapter selectAdapter = new SelectAdapter(context, mStringArray);
//            MyLinearLayoutManager manager = new MyLinearLayoutManager(getActivity());
//            rvSelect.setLayoutManager(manager);
//            rvSelect.setAdapter(selectAdapter);

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;
        }
    }

    class SubjectSpinnerAdapter implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String item = (String) parent.getItemAtPosition(position);
            if (StringUtil.isNotEmpty(item, true)) {
                chooseSubjectStr = item;
            }
            LogUtil.e("选中的科目为：" + item);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    public class AutoPollAdapter extends RecyclerView.Adapter<BaseViewHolder> {

        private final Context mContext;
        private final List<MainInfoBean_1.ObjBean.RecordingClassBean> mData;

        public AutoPollAdapter(Context context, List<MainInfoBean_1.ObjBean.RecordingClassBean> list) {
            this.mContext = context;
            this.mData = list;
        }

        @Override
        public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_record, parent, false);
            BaseViewHolder holder = new BaseViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position) {

            FrameLayout linRecord = holder.getView(R.id.fr_record);
//            int screenWidth = DisplayUtil.getScreenWidth(getActivity());
//            ViewGroup.LayoutParams params = linRecord.getLayoutParams();
//            params.width = screenWidth / 4;
//            linRecord.setLayoutParams(params);

            MainInfoBean_1.ObjBean.RecordingClassBean classBean = null;

            if (mData.size() > 0) {
                if (position < mData.size()) {
                    classBean = mData.get(position);
                } else if (position > mData.size() || position == mData.size()) {
                    classBean = mData.get(position % mData.size());
                }
                ImageView ivRecordBg = holder.getView(R.id.iv_record);
                if (StringUtil.isNotEmpty(classBean.getCover(), true)) {
                    Glide.with(getActivity())
                            .load(classBean.getCover())
                            .apply(GlideConfig.getRoundOptions(10))
                            .into(ivRecordBg);
                }

                if (StringUtil.isNotEmpty(classBean.getVideo_title(), true)) {
                    holder.setText(R.id.tv_record, classBean.getVideo_title());
                }

                MainInfoBean_1.ObjBean.RecordingClassBean finalClassBean = classBean;
                linRecord.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

//                        int recordId = finalClassBean.getId();
//                        ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
//                                .withInt("recordId", recordId).navigation();

                        String recordJson = MGson.newGson().toJson(finalClassBean);
//                        String url = finalClassBean.getVideo_url();
                        LogUtil.e("录播课视频的数据为：" + recordJson);

                        ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
                                .withString("recordJson", recordJson)
                                .withInt("recordId", finalClassBean.getId())
                                .withString("showType", "MainRecord").navigation();

                    }
                });
            }

        }

        @Override
        public int getItemCount() {
            return Integer.MAX_VALUE;
        }
    }


}
